import axios from "axios";
// import { Message } from "element-ui";
import { message, Modal } from 'ant-design-vue'
import ENV from '@/common/config'
/**
 * header 配置
 */
const contentType = 'application/json;charset=UTF-8'

class Request {
  constructor() {
    // 创建axios实例
    this.axiosInstance = axios.create({
      baseURL: location.origin, // 公共接口-本地
      timeout: 1000 * 1000, // 超时时间单位是ms
      withCredentials: true, // 身份验证
      headers: {
        'Content-Type': contentType,
        'X-Requested-With': 'XMLHttpRequest',
		 "Access-Control-Allow-Origin": "*"
      },
    });

    // 配置message窗口仅有一个
    Message.config({
      maxCount: 1,
    });

    // 请求拦截器
    this.axiosInstance.interceptors.request.use(
      (config) => {
        config.$loadingGridOptions = Vue.prototype.$loadingGridOptions;
        config.$globalLoadingResolve = Vue.prototype.$globalLoadingResolve;

        Vue.prototype.$loadingGridOptions = null;
        Vue.prototype.$globalLoadingResolve = null;

        // 执行form-data序列化
        if (!(config.data instanceof Blob)) {
          // 数据转化
          config.data = JSON.stringify(config.data);
        }
        return config;
      },
      (error) => {
        return Promise.reject(error);
      }
    );

    // 响应拦截器
    this.axiosInstance.interceptors.response.use(
      async (response) => {
        const { data, config } = response;
        setTimeout(() => {
          if (config.$loadingGridOptions) {
            config.$loadingGridOptions.loading = false;
          }
          if (config.$globalLoadingResolve) {
            config.$globalLoadingResolve();
          }
        }, 200);

        if (data.code && +data.code !== 200) {
          switch (data.code) {
            case 302: // 登录失效code
              Message.warn('登录失效');
              break;
            case '000000':
              this.onLogout(); //!!!!
              break;
            default:
              Message.error(data.msg || data.message);
              break;
          }

          return Promise.reject(
            'okr请求异常拦截:' +
            JSON.stringify({
              url: config.url,
              code: data.code,
              data: data.data,
              msg: data.msg,
            }) || 'Error'
          );
        } else {
          if (data?.data?.list) {
            return Promise.resolve({
              ...data.data,
              result: data?.data?.list,
              totalCount: +data?.data?.total || +data?.data?.totalCount,
            });
          }
          if (typeof data?.data === 'string') {
            return Promise.resolve({ result: data?.data });
          }
          return Promise.resolve({ ...data.data, result: data?.data });
        }
      },
      (error) => {
        setTimeout(() => {
          if (error?.config?.$loadingGridOptions) {
            error.config.$loadingGridOptions.loading = false;
          }
          if (error?.config?.$globalLoadingResolve) {
            error.config.$globalLoadingResolve();
          }
        }, 200);
        Message.error('未知异常，请联系管理员');
        return Promise.reject(error);
      }
    );
  }

  

  isFile(params) {
    return Object.prototype.toString.call(params) === '[object File]';
  }

  async onLogout() {
    await logOut();
    if (process.env.NODE_ENV !== 'production') {
      return (window.location.href = ENV.devLoginUrl);
    } else {
      return (window.location.href = ENV.proLoginUrl);
    }
  }

  get(url, config) {
    return this.axiosInstance.get(url, config).then((res) => {
      this.message({ config, res });
      return res;
    });
  }

  post(url, data, config) {
    this.requestData = data;
    return this.axiosInstance.post(url, data, config).then((res) => {
      this.message({ config, res });
      return res;
    });
  }

  put(url, data, config) {
    this.requestData = data;
    return this.axiosInstance.put(url, data, config).then((res) => {
      this.message({ config, res });
      return res;
    });
  }

  patch(url, data, config) {
    this.requestData = data;
    return this.axiosInstance.patch(url, data, config).then((res) => {
      this.message({ config, res });
      return res;
    });
  }

  delete(url, config) {
    return this.axiosInstance.delete(url, config).then((res) => {
      this.message({ config, res });
      return res;
    });
  }

  message(data) {

    if (data?.res?.message) {
      NotifyCreate({
        description: data.res.message,
        type: 'success',
      });
      const { content, isError, title } = data?.config?.message?.options;
      return NotifyCreate({
        description: content,
        type: 'success',
        isError: isError ? isError : false,
        msg: title,
      });
    }
  }
}

const service = new Request();

service.axiosInstance.interceptors.response.use(
  response => {
    const { code, msg } = response.data;
    if (code != 200) {
      Message({
        message: msg,
        type: "error",
        duration: 1000
      });
      return Promise.reject();
    }
    return response.data;
  },
  err => {
    Message({
      message: "服务器开小差啦~",
      type: "error",
      duration: 1000
    });
    return Promise.reject(err);
  }
);

export default service;
